//
//  SISSFindTenantViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2017/12/14.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSFindTenantViewController.h"
#import "SISSCommonRentCell.h"
#import "SISSSearchViewController.h"
#import "SISSComboBoxView.h"
#import "SISSRecommendRentOutViewController.h"
#import "SISSTenantDetailViewController.h"
#import "SISSTenantModel.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSJsonRequestNetworkingManager+Resources.h"

static NSString *tenantCellReuseID = @"tenantCellReuseID";
@interface SISSFindTenantViewController ()<UITableViewDelegate,UITableViewDataSource,SISSComboBoxViewDelegate,SISSCommonRentCellDelegate>
/** 租客数组 */
@property (strong, nonatomic) NSMutableArray<SISSTenantModel *> *tenantArr;

/** tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/** 筛选视图 */
@property (weak, nonatomic) SISSComboBoxView *filterView;

/* hintLabel */
@property (weak, nonatomic) UILabel *hintLabel;

/** 可见范围 */
@property (assign, nonatomic) NSInteger visibleRange;
/** 排序规则 */
@property (assign, nonatomic) NSInteger orderAttrs;
/** 区域 */
@property (copy, nonatomic) NSString *region;
/** 街道办 */
@property (copy, nonatomic) NSString *regionDetail;
/** 价格 */
@property (copy, nonatomic) NSString *price;
/** 户型 */
@property (copy, nonatomic) NSString *houseType;
/** 面积 */
@property (copy, nonatomic) NSArray *area;
/** 朝向 */
@property (copy, nonatomic) NSArray *direction;
/** 装修程度 */
@property (copy, nonatomic) NSArray *decoration;
/** pageNo */
@property (assign, nonatomic) NSInteger pageNo;

@end

@implementation SISSFindTenantViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageNo = 1;
    
    // 添加右侧 地图、搜索按钮
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:@selector(searchItemClickAction)];
    //    UIBarButtonItem *locationItem =  [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"map"] style:UIBarButtonItemStylePlain target:self action:@selector(locationItemClickAction)];
    [searchItem setTintColor:COLOR(0x8998A5)];
    //    [locationItem setTintColor:COLOR(0x8998A5)];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    
    // 加载数据
    [self requestFilterSearchTenantData];
    
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf upDownLoadData];
    }];
    
    
    [kSISSRefresh prepareFooterRefresh:self.tableView reloadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeReloadMore;
        [weakSelf reloadMoreData];
    }];
    
    self.tableView.mj_footer.hidden = YES;
}

/**
 右侧搜索按钮点击事件
 */
- (void)searchItemClickAction {
    
    SISSSearchViewController *searchVC = [[SISSSearchViewController alloc] init];
    searchVC.modalPresentationStyle = UIModalPresentationFullScreen;
    searchVC.searchType = SISSSearchTypeTenant;
    [self presentViewController:searchVC animated:NO completion:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.filterView.comBoBoxView dismissPopView];
}



#pragma mark - 代理
#pragma mark -- SISSComboBoxViewDelegate 筛选
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"租金预算"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"意向户型"]) {
        self.houseType = title;
    }
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestFilterSearchTenantData];
    
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestFilterSearchTenantData];
    
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {
    
    if ([title isEqualToString:@"可见范围"]) {
        self.visibleRange = 2;
    } else if ([title isEqualToString:@"面积"]) {
        self.area = @[];
        self.area = subtitles;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = @[];
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = @[];
        self.decoration = subtitles;
    }
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    self.pageNo = 1;
    [self requestFilterSearchTenantData];
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.visibleRange = 1;
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}

#pragma mark -- UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    [tableView tableViewDisplayWithMessage:@"没有找到相关租客！" ifNecessaryForRowCount:self.tenantArr.count];
    if (self.tenantArr.count != 0) {
        return self.tenantArr.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SISSCommonRentCell *cell = [tableView dequeueReusableCellWithIdentifier:tenantCellReuseID forIndexPath:indexPath];
    cell.delegate = self;
    cell.tenantModel = self.tenantArr[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 去除tableView的选中状态
    SISSTenantDetailViewController *vc = [[SISSTenantDetailViewController alloc] init];
    vc.title = @"租客详情";
    vc.isFind = YES;
    SISSTenantModel *tenantModel = self.tenantArr[indexPath.row];
    vc.tenantModel = tenantModel;
    if (tenantModel.read != 1) {
        
        [kNetworkManager setTenantResourceReadWithTenantId:tenantModel.ID success:^(id responseObject) {
            
            if ([responseObject[@"code"] integerValue] == 200) {
                NSLog(@"插入成功！");
            }
            
        } failed:^(NSError *error) {
            
            NSLog(@"%@",error);
        }];
    }
    self.tenantArr[indexPath.row].read = 1;
    [self.tableView reloadData];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - SISSCommonRentCellDelegate
- (void)commonRentCellRecommendButtonDidClick:(UIButton *)button {
    
    SISSCommonRentCell *cell = (SISSCommonRentCell *)button.nextResponder.nextResponder;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    SISSTenantModel *model = self.tenantArr[indexPath.row];
    
    SISSRecommendRentOutViewController *vc = [[SISSRecommendRentOutViewController alloc] init];
    vc.title = @"推荐出租";
    vc.isFind = YES;
    vc.arrId = model.ID;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 点击排序按钮
- (void)sortedButtonDidClick:(UIButton *)button {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor blackColor];
    [alertController addTapDisMissAction];
    
    NSArray *sortArr = @[@"默认排序", @"租金预算从低到高", @"租金预算从高到低"];
    
    for (int i = 0; i < sortArr.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:sortArr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.orderAttrs = i;
            kSISSRefresh.refreshType = SISSRefressTypeUpDown;
            self.pageNo = 1;
            [self requestFilterSearchTenantData];
        }];
        
        [alertController addAction:action];
    }
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownLoadData {
    
    self.pageNo = 1;
    
    [self requestFilterSearchTenantData];
    
}

- (void)reloadMoreData {
    
    self.pageNo += 1;
    
    [self requestFilterSearchTenantData];
}



#pragma mark - 2.4.1 筛选房源、找房源的请求
- (void)requestFilterSearchTenantData {
    
    // 非空处理
    NSString *keyword = self.keyword ? self.keyword : @"";
    NSInteger visibleRange = self.visibleRange == 2 ? self.visibleRange : 1;
    NSInteger orderAttrs = self.orderAttrs ? self.orderAttrs : 0;
    NSString *region = self.region ? self.region : @"不限";
    NSString *regionDetail = self.regionDetail ? self.regionDetail : @"不限";
    NSString *price = self.price ? self.price : @"";
    NSString *houseType = self.houseType ? self.houseType : @"不限";
    NSInteger pageSize = 20;
    
    NSDictionary *parameters = @{@"keyword":keyword,
                                 @"visibleRange":@(visibleRange),
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"saId":[SISSUserAccount shared].saId,
                                 @"soId":[SISSUserAccount shared].soId,
                                 @"sobId":[SISSUserAccount shared].sobId,
                                 @"pageSize":@(pageSize),
                                 @"pageNo":@(self.pageNo),
                                 @"orderAttrs":@(orderAttrs),
                                 @"region":region,
                                 @"regionDetail":regionDetail,
                                 @"price":price,
                                 @"houseType":houseType,
                                 @"area":self.area ,
                                 @"direction":self.direction,
                                 @"decoration":self.decoration
                                 };
    //
    WeakSelf
    [kJsonRequestNetworkingManager requestFilterTenantResourceCooperationWithParameters:parameters success:^(SISSBasePagingModel *baseModel) {
    
            NSArray *tenantResources = [NSArray yy_modelArrayWithClass:[SISSTenantModel class] json:baseModel.data];
    
            if (weakSelf.tenantArr.count != 0 && kSISSRefresh.refreshType == SISSRefressTypeUpDown) {
    
                [weakSelf.tenantArr removeAllObjects];
            }
    
            for (int i = 0; i < tenantResources.count; i++) {
    
                [weakSelf.tenantArr addObject:tenantResources[i]];
            }
    
            //        weakSelf.hintLabel.hidden = NO;
            weakSelf.hintLabel.text = [NSString stringWithFormat:@"共找到%zd条符合条件的信息",weakSelf.tenantArr.count];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.hintLabel.hidden = YES;
            });
    
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    
                [weakSelf.tableView reloadData];
                weakSelf.tableView.mj_footer.hidden = baseModel.total == 0;
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
                if (weakSelf.tenantArr.count >= baseModel.total) {
//                    weakSelf.tableView.mj_footer.hidden = YES;
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }
                
            }];
    
    
        } failed:^(NSError *error) {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            NSLog(@"%@",error);
        }];
}


#pragma mark - 设置UI
- (void)setupSubviews {
    [super setupSubviews];
    
    // 添加筛选视图
    SISSComboBoxView *filterView = [[SISSComboBoxView alloc] initWithFrame:CGRectMake(0, NAVIGATION_HEIGHT, SCREEN_WIDTH, 44) isHouseResource:NO isCooperation:NO priceTitleStr:@"租金预算"];
    filterView.delegate = self;
    
    [self.view addSubview:filterView];
    self.filterView = filterView;
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    // 自动行高
    tableView.estimatedRowHeight = 80;
    tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    [tableView registerClass:[SISSCommonRentCell class] forCellReuseIdentifier:tenantCellReuseID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    // 排序按钮
    UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sortButton setTitle:@"排序" forState:UIControlStateNormal];
    sortButton.layer.cornerRadius = 12;
    sortButton.layer.masksToBounds = YES;
    [sortButton setBackgroundImage:[ImageWithColor imageWithColor:[UIColor darkGrayColor]]  forState:UIControlStateNormal];
    sortButton.titleLabel.font = [UIFont systemFontOfSize:15];
    sortButton.alpha = 0.8;
    [sortButton addTarget:self action:@selector(sortedButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sortButton];
    
    UILabel *hintLabel = [[UILabel alloc] init];
    hintLabel.textAlignment = NSTextAlignmentCenter;
    hintLabel.textColor = [UIColor whiteColor];
    hintLabel.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.8];
    hintLabel.layer.cornerRadius = 12;
    hintLabel.hidden = YES;
    hintLabel.layer.masksToBounds = YES;
    [self.view addSubview:hintLabel];
    self.hintLabel = hintLabel;
    
    // 自动布局
    CGSize sortBtnSize = CGSizeMake(66, 30);
    CGFloat margin = 10;
    CGFloat bottomViewHeight = 0;
    WeakSelf
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.filterView.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.bottom.mas_equalTo(-bottomViewHeight);
    }];
    
    [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view);
        make.size.mas_equalTo(CGSizeMake(250, 30));
        make.bottom.equalTo(weakSelf.view).offset(- 12 * margin);
    }];
    
    [sortButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view).offset(-4 * margin);
        make.bottom.equalTo(weakSelf.view).offset(-8 * margin);
        make.size.mas_equalTo(sortBtnSize);
    }];
    
}

#pragma mark - Getter & Setter

- (NSMutableArray<SISSTenantModel *> *)tenantArr {
    if (!_tenantArr) {
        _tenantArr = [NSMutableArray array];
    }
    return _tenantArr;
}


- (NSString *)keyword {
    
    if (_keyword == nil) {
        _keyword = @"";
    }
    return _keyword;
}

- (NSArray *)area {
    if (_area == nil) {
        _area = [NSArray array];
    }
    return _area;
}

- (NSArray *)direction {
    if (_direction == nil) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    if (_decoration == nil) {
        _decoration = [NSArray array];
    }
    return _decoration;
}


@end
